/**
 * @author: yyq
 * @date: 2025年3月13日 14:02:51
 * @description: 
 */
package com.sheepone.monitor.handler;

import com.sheepone.monitor.codec.SheeponeContentInboundConverter;
import com.sheepone.monitor.codec.SheeponePackage;
import com.sheepone.monitor.enums.SerializationAlgorithmsEnum;
import com.sheepone.monitor.enums.SheeponePackageTypeEnum;
import com.sheepone.webdev.log.WebDevLogger;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author: yyq
 * @date: 2025年3月13日 14:02:51
 * @description:
 */
public abstract class AbstractSheeponeContentInboundHandler<R> extends ChannelInboundHandlerAdapter
        implements SheeponeContentInboundConverter<R> {

    private WebDevLogger logger = WebDevLogger.getLogger(AbstractSheeponeContentInboundHandler.class);
    private SheeponePackageTypeEnum type;

    public AbstractSheeponeContentInboundHandler(SheeponePackageTypeEnum type,
            SerializationAlgorithmsEnum serialization) {
        this.type = type;
    }

    protected abstract void channelRead0(ChannelHandlerContext ctx, R msg) throws Exception;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof SheeponePackage) || ((SheeponePackage) msg).getType() != type) {
            ctx.fireChannelRead(msg);
            return;
        }
        SheeponePackage sp = (SheeponePackage) msg;
        if (sp.getType() != type) {
            ctx.fireChannelRead(msg);
            return;
        }
        try {
            channelRead0(ctx, fromBytes(sp.getContent(), sp.getSerialization()));
        } catch (Exception e) {
            logger.error("{} channelRead error", this.getClass().getName(), e.getMessage());
        } finally {
            ctx.fireChannelRead(msg);
        }
    }

}
